package com.xzc.algorithm.data_structure_ke.LinkedList;

import com.xzc.algorithm.data_structure_ke.ArrayList.queue.Queue;
import lombok.Data;

public class Link2Way<T> {

    @Data
    private static class Node<T> {
        private T t;
        private Node next, pre;

        public Node(T t, Node next) {
            this.t = t;
            this.next = next;
        }

        public Node(T t) {
            this.t = t;
            this.next = null;
        }
    }

    private Node<T> head;
    private Node<T> tail;
    private int size;

    public boolean isEmpty() {
        return size == 0;
    }

    public int getSize() {
        return size;
    }

    public void enqueue(T t) throws Exception {
        if (tail == null) {
            tail = new Node<>(t);
            head = tail;
        } else if (head.next == null) {
            tail = new Node<>(t);
            head.next = tail;
        } else {
            tail.next = new Node<>(t);
            tail = tail.next;
        }
        size++;
    }

    public T dequeue() throws Exception {
        if (tail == null)
            throw new Exception("isEmpty");
        Node<T> tmp = head;
        if (head.next == null) {
            head = null;
            tail = null;
            size--;
            return tmp.t;
        }
        head = head.next;
        tmp.next = null;
        size--;
        return tmp.t;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        if (!isEmpty()) {
            Node tmp = head;
            for (int i = 0; i < size; i++) {
                System.out.println(tmp);
                sb.append(tmp.t).append(",");
                tmp = tmp.next;
            }
        }
        sb.append("]");
        sb.append(" size=").append(size);
        if (!isEmpty()) {
            sb.append(" head=").append(head.t);
            sb.append(" tail=").append(tail.t);
        }
        return sb.toString();
    }
}
